import Vue from 'vue';
import {
    api,
} from '@/lib/api';
import {
    url,
    isArray,
    currency,
} from '@/lib/utils';

import { Module } from 'vuex';
import { RootState } from '@/types/store';

export interface OrderState {
    /** 订单列表 */
    list: {
        [status: string]: ListWrap<Order.ListItem> & ListReq;
    };
    /** 订单详情 */
    detail: {
        [orderId: number]: Order.Detail;
    };
    /** 在线管理-订单详情 */
    manageorderoetail: {
        [orderId: number]: Order.Detail;
    }
    /** 代金券id */
    couponId: number | null;
    /** 将使用的addressId */
    addressId: number | null;
    /** 等待支付 */
    pendingCart: {
        [shopId: number]: Shop.CartItem[];
    };
}

const m: Module<OrderState, RootState> = {
    namespaced: true,
    state: {
        /** status => wrap */
        list: {},
        /** 订单详情 */
        detail: {},
        // 在线管理订单详情
        manageorderoetail: {},
        /** 代金券id */
        couponId: null,
        /** 将使用的addressId */
        addressId: null,
        /** 等待支付 */
        pendingCart: {},
    },
    mutations: {
        /**
         * 订单列表
         */
        initList(state, { status }) {
            Vue.set(state.list, status, {
                list: [],
                loaded: false,
                req: false,
            });
        },
        concatList(state, { status, list }) {
            for (const order of list) {
                if (!isArray(order.detail)) {
                    continue;
                }
                for (const item of order.detail) {
                    item.price_text = currency(item.price);
                }
            }
            state.list[status].list.push(...list);
        },
        setListLoaded(state, { status, loaded }) {
            state.list[status].loaded = loaded;
        },
        setListReq(state, { status, req }) {
            state.list[status].req = req;
        },
        /**
         * 记录订单详情
         */
        setDetail(state, { orderId, detail }) {
            if (isArray(detail.detail)) {
                for (const item of detail.detail) {
                    item.price_text = currency(item.price);
                }
            }
            Vue.set(state.detail, orderId, detail);
        },

        /**
         * 记录在线管理-订单详情
         */
        setManageOrderDetail(state, { orderId, detail }) {
            if(detail){
                if (isArray(detail.detail)) {
                    for (const item of detail.detail) {
                        item.price_text = currency(item.price);
                    }
                }
                Vue.set(state.manageorderoetail, orderId, detail);
            }else{
                Vue.set(state.manageorderoetail, orderId, detail);
            }

            // if (isArray(detail.detail)) {
            //     for (const item of detail.detail) {
            //         item.price_text = currency(item.price);
            //     }
            // }
            // Vue.set(state.detail, orderId, detail);
        },
        /**
         * 记录代金券id
         */
        setCouponId(state, couponId) {
            state.couponId = couponId;
        },
        /**
         * 记录将使用的addressId
         */
        setAddressId(state, addressId) {
            state.addressId = addressId;
        },
        /**
         * 等待支付的cart
         */
        setPendingCart(state, cart) {
            state.pendingCart = cart;
        },
    },

    actions: {
        /**
         * 获取列表
         */
        async getList({ state, commit }, { offset, count, status, forceUpdate }) {
            let wrap = state.list[status];
            if (!wrap || forceUpdate) {
                commit('initList', { status });
                wrap = state.list[status];
            }
            if (wrap.loaded || wrap.req) {
                return;
            }
            const end = offset + count;
            const length = wrap.list.length;
            if (end <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = end - offset;
            }
            commit('setListReq', { status, req: true });
            const data: any = {
                offset,
                count,
            };
            if (status !== 'all') {
                data.status = status;
            }
            const res = await api.get({
                url: `${url}/api/order/list`,
                data,
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatList', {
                    status,
                    list,
                });
                if (list.length < count) {
                    commit('setListLoaded', {
                        status,
                        loaded: true,
                    });
                }
            }
            commit('setListReq', { status, req: false });
            return res;
        },
        /**
         * 获取订单详情
         */
        async getDetail(context, { orderId }) {
            const res = await api.get({
                url: `${url}/api/order/detail`,
                data: {
                    id: orderId,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                context.commit('setDetail', {
                    orderId,
                    detail: res.data.data,
                });
            }
            return res;
        },
        /**
         * 获取在线管理-订单详情
         */
        async getManageOrderDetail(context, { orderId }) {
            const res = await api.get({
                url: `${url}/api/order/order_detail`,
                data: {
                    id: orderId,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                context.commit('setManageOrderDetail', {
                    orderId,
                    detail: res.data.data,
                });
            }
            return res;
        },


        /**
         * 创建订单
         */
        async createPkgOrder(context, { packageId, referrerId, spec, couponId, deliverDate, name, mobile, isPrepay, remark, hasDiscount, payType, balance_pay }) {
            const res = await api.post({
                url: `${url}/api/package/order`,
                data: {
                    package_id: packageId,
                    referrer_id: referrerId,
                    spec,
                    coupon_id: couponId,
                    deliver_date: deliverDate,
                    name,
                    mobile,
                    is_prepay: isPrepay,
                    remark,
                    has_discount: hasDiscount,
                    pay_type: payType,
                    balance_pay: balance_pay,
                },
            });
            return res;
        },
        /**
         * 创建订单
         */
        async createProductOrder(context, { goods_id, spec, referrerId, couponId, name, mobile, address, delivery, isPrepay, remark, hasDiscount, payType, balance_pay }) {
            const res = await api.post({
                url: `${url}/api/good/order`,
                data: {
                    goods_id,
                    spec,
                    referrer_id: referrerId,
                    coupon_id: couponId,
                    name,
                    mobile,
                    address,
                    delivery,
                    is_prepay: isPrepay,
                    remark,
                    has_discount: hasDiscount,
                    pay_type: payType,
                    balance_pay: balance_pay
                },
            });
            return res;
        },
        // 发送模板消息 -- 会员下单后未支付退出提示    orderId 订单号,template_id 模板id,pickType 取货方式(套系自取) payType 支付方式
        async checkBackSendMsg(context, { orderId,type, pickType, payType }){
            let data = {
                id: orderId,
                template_id: ''
            };
            if(type == 'taoxi'){
                // 套系 自取 商城 可选
                if(payType == 'all'){
                    data.template_id = '37'
                }
                if(payType == 'book'){
                    data.template_id = '36'
                }
            }
            if(type == 'shop'){
                // 自取
                if(pickType == false){
                    // 套系 自取 商城 可选
                    if(payType == 'all'){
                        data.template_id = '37'
                    }
                    if(payType == 'book'){
                        data.template_id = '36'
                    }
                }
                if(pickType == true){
                    // 套系 自取 商城 可选
                    if(payType == 'all'){
                        data.template_id = '39'
                    }
                    if(payType == 'book'){
                        data.template_id = '38'
                    }
                }
            }
            const res = await api.get({
                url: `${url}/api/order/sendMsg`,
                data: data,
            });
            return res;
        },
        /**
         * 支付
         */
        async pay(context, { orderId,payType }) {
            const res = await api.post({
                url: `${url}/api/order/pay_param`,
                data: {
                    id: orderId,
                    pay_type:payType
                },
            });
            return res;
        },
        /**
         * 查询订单支付状态
         */
        async getPayStatus(context, { id, type }) {
            const reqUrl = `${url}/api/order/` + (type === 'product' ? 'combined_order_status' : 'status');
            const res = await api.get({
                url: reqUrl,
                data: {
                    id,
                },
            });
            return res;
        },
        /**
         * 订单详情
         */
        async getCombinedOrderDetail(context, { orderId }) {
            const response = await api.get({
                url: `${url}/api/order/combined_order_detail`,
                data: {
                    id: orderId,
                },
            });
            const rdata = response.data;
            return rdata;
        },
        /**
         * 评价订单
         */
        async comment(context, { orderId, productId, score, content, images }) {
            const res = await api.post({
                url: `${url}/api/order/comment`,
                data: {
                    order_id: Number(orderId),
                    id: Number(productId),
                    score,
                    content: content || null,
                    image: images.length ? images : null,
                },
            });
            return res;
        },
        /**
         * 确认收货
         */
        async confirm(context, { orderId }) {
            const res = await api.get({
                url: `${url}/api/order/finish`,
                data: {
                    id: orderId,
                },
            });
            return res;
        },
    },
};

export default m;
